# 打开文件
# 参数1:文件名， 参数2: 打开方式， 参数3: 编码方式
# fp => 文件句柄
# 读取文件
# readlines从光标当前位置开始读取到文件末尾 => list
fp = open("./test", "r", encoding="utf-8")
content1 = fp.readlines()
print(type(content1), content1)
# 移动文件指针(移动到文件开头)
fp.seek(0)
# read
content2 = fp.read()
print(type(content2), content2)
# readline -> 读取一行数据
fp.seek(0)
line = fp.readline()
print(type(line), line)
# 关闭文件
fp.close
# 添加异常处理
# try:
#     print("读取文件")
#     fp = open("./test","r",encoding="utf-8")
#     content1 = fp.readlines()
#     print(type(content1))
#     print(content1)
#     # 移动文件指针(移动到文件开头)
#     fp.seek(0)
#     # read
#     content2 = fp.read()
#     print(type(content2))
#     print(content2)
#     # readline -> 读取一行数据
#     fp.seek(0)
#     line = fp.readline()
#     print(type(line))
#     print(line)
#     print()
# except Exception as ex:
#     print("读取文件失败",ex)
# finally:
#     print("清理数据，释放空间")
#     # 关闭文件
#     fp.close
try:
    with open("./test", "r", encoding="utf-8") as fp:
        content1 = fp.readlines()
        print(type(content1), content1)
        # 移动文件指针(移动到文件开头)
        fp.seek(0)
        # read
        content2 = fp.read()
        print(type(content2), content2)
        # readline -> 读取一行数据
        fp.seek(0)
        line = fp.readline()
        print(type(line), line)
except FileExistsError as ex:
    print("文件不存在")
except Exception as ex:
    print("未知错误")

# 写入数据到文件
# r => 读
# w => 写(如果文件不存在会帮我们创建一个文件)，如果文件存在，会覆盖原来的内容
# a => 追加(如果文件不存在，会创建)
# r+ => 读写
# rw => 读写

try:
    with open("./test","w",encoding="utf-8") as fp:
        # 数据写到当前文件指针的位置
        # 2 => 文件末尾， 0 => 移动0字节
        fp.seek(0,2)
        fp.write("hello world!")
except FileExistsError as ex:
    print("文件不存在")
except Exception as ex:
    print("未知错误",ex)


# 从键盘中接收十行数据，以行为单位写到文件。test2.txt
# 如果是第二次执行的时候，内容是追加到后面的
# 如果能封装函数的，尽量去封装，异常处理可能会报错，就加异常处理
def write_lines_to_file(filename:str) -> None:
    try:
        with open(filename, "a", encoding="utf-8") as file:
            for i in range(10):
                line = input(f"请输入第{i+1}行数据: ")
                file.write(line + "\n")
        print("数据写入成功！")
    except Exception as ex:
        print("写入过程中出现异常:", ex)


write_lines_to_file("./test2.txt")
